package com.liwc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.liwc.util.CheckMobile;
import com.liwc.util.Md5Util;

/**
 * 登录
 * 
 * 功能:
 * 
 * @author liwc
 * 
 */
@Controller
public class LoginController {

	// log
	private static final Logger log = LoggerFactory.getLogger(LoginController.class);


	/**
	 * 打开登录入口
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "login")
	public String login(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		model.addAttribute("title", "用户登录");
//		if (CheckMobile.check(request, response)) {
//			return "mobile/login";
//		} else {
			return "login";
//		}
	}

	/**
	 * 登陆验证
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="loginVerfiy", method=RequestMethod.POST )
	public String loginVerfiy(HttpServletRequest request, Model model){
		
		String username = request.getParameter("username");
		String pwd = request.getParameter("pwd");
		String verifyCode = request.getParameter("verifyCode");
		String kaptchaCode = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		
		log.debug("生成的验证码："+kaptchaCode +", 输入的验证码："+verifyCode );
		
		if(!kaptchaCode.equals(verifyCode)){
			model.addAttribute("msg", "验证码输入不正确！");
			model.addAttribute("title", "用户登录");
			return "login";
		}
		
		boolean rememberMe = false;
		String md5Pwd = Md5Util.generatePassword(pwd);
		
		try {
			UsernamePasswordToken token = new UsernamePasswordToken(username, md5Pwd, rememberMe);
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);
			return "redirect:/layout/layout";
			
		} catch (LockedAccountException lae) {
			model.addAttribute("msg", "账号已被禁用");
		} catch (AuthenticationException ae) {
			model.addAttribute("msg", "账号或密码错误");
		} catch (Exception e) {
			model.addAttribute("msg", "登录异常");
		}
		
		return "login";
	}
	
	
	@RequestMapping("logOut")
	public String logOut(HttpServletRequest request){
		
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		
		return "redirect:/login";
	}

}
